package rexsee.cartoon;

import java.util.ArrayList;

import rexsee.core.utilities.Utilities;
import rexsee.xml.XmlElement;

public class Action {

	public final Actions actions;

	public final String id;
	public final String baseDir;
	public final int actionWidth;
	public final int actionHeight;

	public final ArrayList<Frame> list = new ArrayList<Frame>();

	public Action(Actions resources, int canvasWidth, int canvasHeight, XmlElement element) {

		this.actions = resources;

		if (element.attributes != null) {

			id = element.attributes.get(TagName.ATTR_ID);

			String baseDir = element.attributes.get(TagName.ATTR_ACTION_BASEDIR);
			if (baseDir != null) {
				baseDir = baseDir.trim();
				while (baseDir.endsWith("/")) {
					baseDir = baseDir.substring(0, baseDir.length() - 1);
				}
				String check = baseDir.toLowerCase();
				if (!check.startsWith("http://") && !check.startsWith("https://") && !check.startsWith("file://")) baseDir = null;
			}
			this.baseDir = baseDir;

			String size = element.attributes.get(TagName.ATTR_SIZE);
			if (size != null && size.contains("x")) {
				String[] c = size.trim().toLowerCase().split("x");
				actionWidth = Utilities.getInt(c[0], canvasWidth);
				actionHeight = Utilities.getInt(c[1], canvasHeight);
			} else {
				actionWidth = canvasWidth;
				actionHeight = canvasHeight;
			}

		} else {
			id = null;
			baseDir = null;
			actionWidth = canvasWidth;
			actionHeight = canvasHeight;
		}

		if (element.childs != null && element.childs.size() > 0) {
			for (int i = 0; i < element.childs.size(); i++) {
				Frame frame = new Frame(this, element.childs.get(i));
				if (frame.src != null) list.add(frame);
			}
		}

	}

	public int size() {
		return list.size();
	}
	public void removeFrame(int i) {
		list.remove(i);
	}
	public Frame getFrame(int i) {
		return (i > list.size() - 1) ? null : list.get(i);
	}

	public void load() {
		for (int i = 0; i < list.size(); i++) {
			Frame frame = list.get(i);
			if (frame != null) frame.load();
		}
	}
	public void destroy() {
		for (int i = 0; i < list.size(); i++) {
			Frame frame = list.get(i);
			if (frame != null) frame.destroy();
		}
	}

	public void destroyPartially(ArrayList<Frame> usedFrame) {
		for (int i = 0; i < list.size(); i++) {
			Frame frame = list.get(i);
			if (frame != null && !usedFrame.contains(frame)) frame.destroy();
		}
	}

}
